<?php
namespace api\controllers;

use api\models\Order;
use yii\data\ActiveDataProvider;
use yii\filters\auth\HttpBasicAuth;
use yii\filters\auth\HttpBearerAuth;
use yii\filters\auth\QueryParamAuth;
use yii\helpers\ArrayHelper;
use yii\rest\ActiveController;
use Yii;

class OrderController extends ActiveController
{
    //public $modelClass = 'api\models\resource\OrderResource';
    public $modelClass = 'api\models\Order';

    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(),[
            'authenticatior'=>[
             //   'class'=>QueryParamAuth::className(),
               // 'class'=>HttpBasicAuth::className(),
                'class'=>HttpBearerAuth::className(),
            ]
        ]);
    }

    // 2. HTTP基本认证
    /*public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(),[
            'authenticatior'=>[
                'class'=>HttpBasicAuth::className(),
                'auth'=>function($username,$password){
                    $user= User::find()->where(['username'=>$username])->one();
                    if($user->validatePassword($password)){
                        return $user;
                    }
                    return null;
                }
            ]
        ]);
    }*/

    public function actions()
    {
        $actions = parent::actions();
        //unset($actions['index']);   // 删除默认方法
        return $actions;
    }



    /**
     * 分页
     * */
    public function actionPage(){
        $get = Yii::$app->request->get();
        $modelClass = $this->modelClass;
        return new ActiveDataProvider([
            'query'=>$modelClass::find()->asArray(),
            'pagination'=>['pageSize'=>$get['pageSize']]
        ]);
    }

    // 关键字搜索
    public function actionSearch(){
        if(Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            $query = Order::find()
                ->select("*")
                ->where("1=1")
                ->andFilterWhere(['like','order_num',$post['order_num']]);

            if(!empty($post['page'])&&!empty($post['limit'])){
                $query->offset(($post['page']-1)*$post['limit'])
                    ->limit($post['limit']);
            }

            $result = $query
                ->orderBy(['id'=>SORT_ASC])
                ->asArray()
                ->all();
            return $result;
        }
    }

}